<!-- Login && registry -->
<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import {
  getCaptcha,
  register,
  doLogin,
  sendMail,
  forgetPwd,
  getUserInfo
} from '@/request/usr'
import { useTokenStore, useFilePidStore, useUserStore } from '@/stores/index'
import { ElMessage } from 'element-plus'
const tokenStore = useTokenStore()
const router = useRouter()
const userStore = useUserStore()
//邮箱类型
// 邮箱发送测试
const maildisabled = ref(false)
const buttonText = ref('发送验证码')
const setMailCode = () => {
  if (ruleFrom.value.email === '') {
    ElMessage({
      type: 'error',
      message: '请输入邮箱'
    })
    return
  }
  //发送邮箱请求
  sendMail(ruleFrom.value.email).then((res) => {
    console.log(res)
  })
  // 邮箱按钮定时器
  let count = 60
  const timer = setInterval(() => {
    count--
    buttonText.value = ` ${count}秒再试`
    if (count > 0) {
      buttonText.value = `${count}秒再试`
    } else {
      clearInterval(timer)
      buttonText.value = '发送验证码'
      count = 60
      maildisabled.value = false
    }
  }, 1000)
  maildisabled.value = true
}

//操作类型0:注册,1:登录,2:重置密码
const opType = ref(1)
const showPanel = (type) => {
  opType.value = type
}
//数据
const ruleFrom = ref({
  username: 'admin',
  // nickName: '',
  password: 'admin',
  repassword: '',
  email: '',
  emailCode: '',
  code: '',
  uuid: ''
})
//二次密码校验
const validatePass = (rule, value, callback) => {
  if (ruleFrom.value.password === '') {
    callback(new Error('请再次输入密码'))
  } else if (ruleFrom.value.password !== ruleFrom.value.repassword) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}
//校验
const rules = ref({
  username: [
    {
      required: true,
      message: '请输入用户名！！',
      trigger: 'blur'
    },
    {
      min: 7,
      max: 18,
      message: '用户名长度为7-11位',
      trigger: 'blur'
    },
    {
      pattern: /^[a-zA-Z][a-zA-Z0-9]{0,}$/,
      message: '需要由字母数字组成'
    }
  ],
  password: [
    {
      required: true,
      message: '请输入密码！！',
      trigger: 'blur'
    },
    {
      min: 8,
      max: 18,
      message: '长度长度为8-18位',
      trigger: 'blur'
    },
    {
      pattern: /^[a-zA-Z][a-zA-Z0-9]{0,}$/,
      message: '需要由字母数字组成'
    }
  ],
  repassword: [
    {
      required: true,
      message: '请输入密码！！',
      trigger: 'blur'
    },
    {
      min: 8,
      max: 18,
      message: '长度长度为8-18位',
      trigger: 'blur'
    },
    { validator: validatePass, trigger: 'blur', required: true }
  ],
  code: [
    {
      required: true,
      message: '请输入验证',
      trigger: 'blur'
    }
  ],
  emailCode: [
    {
      required: true,
      message: '请输入邮箱验证！！',
      trigger: 'blur'
    }
  ],
  email: [
    {
      required: true,
      message: '请输入邮箱',
      trigger: 'blur'
    },
    {
      type: 'email',
      message: '请输入正确邮箱',
      trigger: ['blur', 'change']
    }
  ]
})

//初始化验证图片
const codeImgUrl = ref('')
// 刷新验证码图片
const refreshCode = async () => {
  // 向后端接口发送请求，获取验证码图片URL
  const res = await getCaptcha()
  codeImgUrl.value = 'data:image/png;base64,' + res.img
  ruleFrom.value.uuid = res.uuid
}
// // 初始化时刷新一次验证码图片
refreshCode()

tokenStore.setToken(1)
// 提交表单登录,注册,找回密码
let submitForm = async () => {
  if (opType.value === 1) {
    //发登录请求
    let userId = ref()
    await doLogin(ruleFrom.value)
        .then((res) => {
          console.log(res)
          useTokenStore().setToken(res.data.token)
          useFilePidStore().setFilePid(res.data.filePid)
          userId.value = res.data.userInfo.userId
          console.log(123)
        })
        .catch(() => {
          refreshCode()
          return
        })
    await getUserInfo(userId.value).then((res) => {
      // console.log(res)
      // localStorage.setItem('filePid', res.filePid)
      useFilePidStore().setFilePid(res.filePid)
      useFilePidStore().setRecoverPid(res.filePid)
      useFilePidStore().setUploadingPid(res.filePid)
      localStorage.setItem('userId', res.userId)
      userStore.setUserInfo(res)
    })
    router.push('/allview')
  } else if (opType.value === 0) {
    // 发注册请求校验
    if (ruleFrom.value.email === '') {
      ElMessage.error('邮箱不能为空')
      return
    } else if (ruleFrom.value.emailCode === '') {
      ElMessage.error('请先获取邮箱验证码')
      return
    } else if (ruleFrom.value.password !== ruleFrom.value.repassword) {
      ElMessage.error('两次输入的密码不一致')
      return
    }
    register(ruleFrom.value).then((res) => {
      console.log(res)
      // @ts-ignore
      res.code === 200 ? (opType.value = 1) : ''
    })
  } else if (opType.value === 2) {
    // 发密码重置请求
    if (ruleFrom.value.email === '') {
      ElMessage.error('邮箱不能为空')
      return
    } else if (ruleFrom.value.emailCode === '') {
      ElMessage.error('请先获取邮箱验证码')
      return
    } else if (
        ruleFrom.value.password === '' ||
        ruleFrom.value.repassword === ''
    ) {
      ElMessage.error('密码不能为空')
      return
    } else if (ruleFrom.value.password === ruleFrom.value.repassword) {
      ElMessage.error('两次输入的密码不一致')
      return
    }
    forgetPwd(ruleFrom.value).then((res) => {
      console.log(res)
    })
  }
}
const ruleFormRef = ref()
// const resetForm = () => {
//   ruleFormRef.value.resetFields()
// }
const Userdisabled = ref(false)
</script>
<template>
  <div class="backgrounds">
    <div class="left">
      <div>
        The world's widest is the ocean, wider than the ocean is the sky, wider
        than the sky is the human mind. - "Les Miserables."
      </div>
    </div>
    <div class="right">
      <el-form
          class="login-boxs"
          ref="ruleFormRef"
          :model="ruleFrom"
          label-width="auto"
          :rules="rules"
          status-icon
      >
        <div class="loader_logo"></div>
        <div class="logo-head">
          <img
              src="@/assets/logo.png"
              style="width: 100px; opacity: 0.5"
              alt=""
          />
          <span>集合号</span>
        </div>
        <div class="content">
          <!-- 用户名 -->
          <el-form-item prop="username" v-if="opType === 0 || opType === 1">
            <template #label>
              <span>用户名</span>
            </template>
            <el-input
                :disabled="Userdisabled"
                placeholder="请输入账号（由字母数字组成）"
                v-model="ruleFrom.username"
            />
          </el-form-item>
          <!-- 昵称 -->
          <!-- <el-form-item prop="nickName" v-if="opType === 0">
            <template #label>
              <span>用户账号</span>
            </template>
            <el-input
              :disabled="Userdisabled"
              placeholder="请输入昵称（由字母数字组成）"
              v-model="ruleFrom.nickName"
            />
          </el-form-item> -->
          <!-- 修改或注册邮箱发送验证  -->
          <el-form-item prop="email" v-if="opType == 2 || opType == 0">
            <template #label>
              <span>邮箱</span>
            </template>
            <el-input placeholder="请输入邮箱" v-model="ruleFrom.email" />
          </el-form-item>
          <!-- 邮箱验证码校验 -->
          <el-form-item prop="emailCode" v-if="opType == 2 || opType == 0">
            <template #label>
              <span>邮箱验证码</span>
            </template>
            <el-input placeholder="邮箱验证码" v-model="ruleFrom.emailCode">
              <template #suffix>
                <el-button
                    link
                    :disabled="maildisabled"
                    @click="setMailCode"
                    type="primary"
                >
                  {{ buttonText }}
                </el-button>
              </template>
            </el-input>
          </el-form-item>
          <!-- 登录密码 -->
          <el-form-item
              prop="password"
              v-if="opType == 0 || opType == 1 || opType == 2 || opType == 3"
          >
            <template #label>
              <span>密码</span>
            </template>
            <el-input
                placeholder="请输入密码"
                v-model="ruleFrom.password"
                show-password
            ></el-input>
          </el-form-item>
          <!-- 注册二次确认密码 -->
          <el-form-item
              prop="repassword"
              v-if="opType == 0 || opType == 2 || opType == 3"
          >
            <template #label>
              <span>确认密码</span>
            </template>
            <el-input
                placeholder="再次确认密码"
                v-model="ruleFrom.repassword"
                show-password
            ></el-input>
          </el-form-item>

          <!-- 验证码 -->
          <el-form-item prop="code" v-if="opType == 1">
            <template #label>
              <span>验证码</span>
            </template>
            <el-input v-model="ruleFrom.code" style="width: 60%"></el-input>
            <!-- 图片验证码 -->
            <el-image
                style="
                cursor: pointer;
                width: 39%;
                height: 90%;
                border-radius: 5px;
                /* margin-left: 10px; */
              "
                :src="codeImgUrl"
                fit="cover"
                @click="refreshCode"
            />
          </el-form-item>
          <div class="toggle-button">
            <span @click="showPanel(1)" v-if="opType == 0 || opType == 2"
            ><a>去登录</a></span
            >
            <span @click="showPanel(2)" v-if="opType == 1 || opType == 0"
            ><a>忘记密码</a></span
            >
            <span @click="showPanel(0)" v-if="opType == 1 || opType == 2"
            ><a>去注册</a></span
            >
            <!-- <span @click=showPanel(3)><a>修改密码（临时）</a></span> -->
          </div>
          <el-form-item class="button">
            <el-button v-if="opType == 1" type="primary" @click="submitForm()">
              <span>登录</span>
            </el-button>
            <el-button v-if="opType == 0" type="primary" @click="submitForm()">
              <span>注册</span>
            </el-button>
            <el-button v-if="opType == 2" type="primary" @click="submitForm()">
              <span>重置密码</span>
            </el-button>
            <el-button v-if="opType == 3" type="primary" @click="submitForm()">
              <span>提交新密码</span>
            </el-button>
          </el-form-item>
        </div>
        <!-- </div> -->
      </el-form>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.backgrounds {
  height: 100vh;
  width: 100%;
  background-image: url(../../assets/15.webp);
  background-size: cover;
  display: flex;
  .left {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 55%;
    height: 100vh;
    div {
      font-size: 1.5em;
      margin: 50px;
      color: white;
      text-indent: 2em;
    }
  }
  .right {
    width: 45%;
    display: flex;
    justify-content: center;
    align-items: center;
    background: rgb(0 0 0 / 6%);
    backdrop-filter: blur(14px);
    -webkit-backdrop-filter: blur(14px);
    .login-boxs {
      margin: 0 10px;
      .logo-head {
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 30px;
        color: white;
        font-weight: 900;
        text-shadow: 0 0 2px black;
        filter: drop-shadow(0 0 5px rgb(255, 255, 255));
      }
      .content {
        .el-form-item {
          // font-size: larger;
          height: 5vh;
          span {
            color: white;
          }
        }
        .toggle-button {
          display: flex;
          width: 100%;
          justify-content: space-around;
          color: rgb(255, 255, 255);
          margin: 20px 0;
          span {
            cursor: pointer;
          }
          span:hover {
            text-shadow: 0 0px 3px rgb(0, 0, 0);
          }
        }
        .button {
          .el-button {
            width: 100%;
          }
        }
      }
    }
  }
}
@media (max-width: 570px) {
  .backgrounds {
    .left {
      display: none;
    }
    .right {
      width: 100%;
    }
  }
}
</style>
